<template>
  <div>
    <!-- 告警通知 -->
    <el-alert
      title="尊敬的客户，当100M带宽达到峰值，为避免24小时，体验服务带宽可能主机性能，实例性能中进行预警。"
      type="warning"
      show-icon
      :closable="true"
    >
      <el-link type="primary" class="alert-link">马上升级</el-link>
    </el-alert>

    <!-- 主要内容区域 -->
    <div class="monitor-content">
      <el-row :gutter="20">
        <!-- 左侧信息区域 -->
        <el-col :span="8">
          <!-- 配置信息卡片 -->
          <el-card class="info-card" shadow="never">
            <div slot="header" class="card-header">
              <span>配置信息</span>
              <el-button type="text" icon="el-icon-refresh" @click="handleBatch">刷新</el-button>
            </div>
            <div class="info-list">
              <div class="info-item">
                <span class="label">实例名称</span>
                <span class="value">{{currentResource.resourceName}}</span>
              </div>
              <div class="info-item">
                <span class="label">实例状态</span>
                <span class="value">
                   <el-tag size="small" v-if="currentResource.other1=='0'" type="warning">未启动</el-tag>
                    <el-tag size="small" v-if="currentResource.other1=='1'" type="success">运行中</el-tag>
                   <el-tag size="small" v-if="currentResource.other1=='2'" type="warning">关闭</el-tag>
                   <el-tag size="small" v-if="currentResource.other1=='4'" type="warning">未启动</el-tag>
                </span>
              </div>
              <div class="info-item">
                <span class="label">实例规格</span>
                <span class="value">{{currentResource.productSpecDesc}}</span>
              </div>
              <div class="info-item">
                <span class="label">磁盘大小</span>
                <span class="value">{{currentResource.disksize}}GB</span>
              </div>
              <div class="info-item">
                <span class="label">备份天数</span>
                <span class="value">3天</span>
              </div>
              <div class="info-item">
                <span class="label">带宽</span>
                <span class="value">2M</span>
              </div>
              <div class="info-item">
                <span class="label">系统版本</span>
                <span class="value">{{currentResource.other2}}</span>
              </div>
              <div class="info-item">
                <span class="label">到期时间</span>
                <span class="value">剩余{{ currentResource.dayval }}天</span>
              </div>
              <div class="info-item">
                <span class="label">远程地址</span>
                <span class="value copy-value" @click="copyToClipboard(currentResource.other4)">
                 {{currentResource.other4}}
                  <i class="el-icon-document-copy"></i>
                </span>
              </div>
            </div>
          </el-card>

          <!-- 安全信息卡片 -->
          <el-card class="security-card" shadow="never">
            <div slot="header" class="card-header">
              <span>安全</span>
              <el-tooltip content="安全评分说明" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </div>
            <div class="security-content">
              <div class="security-score">
                <el-progress
                  type="circle"
                  :percentage="96"
                  :width="120"
                  :stroke-width="10"
                  color="#67C23A"
                >
                  <template slot-scope="{ percentage }">
                    <div class="progress-content">
                      <span class="percentage">{{ percentage }}</span>
                      <span class="unit">分</span>
                      <div class="status">安全</div>
                    </div>
                  </template>
                </el-progress>
              </div>
              <div class="security-items">
                <div class="security-item">
                  <span class="label">网络防护</span>
                  <span class="value">
                    <i class="el-icon-success status-icon"></i> 正常
                  </span>
                </div>
                <div class="security-item">
                  <span class="label">主机防护</span>
                  <span class="value">
                    <i class="el-icon-success status-icon"></i> 正常
                  </span>
                </div>
                <div class="security-item">
                  <span class="label">网络防护版本</span>
                  <span class="value">网络防护高级版</span>
                </div>
                <div class="security-item">
                  <span class="label">主机防护版本</span>
                  <span class="value">主机防护高级版</span>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 网络与域名卡片 -->
          <el-card class="network-card" shadow="never">
            <div slot="header" class="card-header">
              <span>网络与域名</span>
            </div>
            <div class="network-content">
              <div class="ip-item">
                <span class="label">IP（公）</span>
                <span class="value copy-value" @click="copyToClipboard(currentResource.other4)">
                  {{currentResource.other4}}
                  <i class="el-icon-document-copy"></i>
                </span>
              </div>
              <div class="ip-item">
                <span class="label">IP（内）</span>
                <span class="value copy-value" @click="copyToClipboard(currentResource.other3)">
                  {{currentResource.other3}}
                  <i class="el-icon-document-copy"></i>
                </span>
              </div>
              <div class="domain-item">
                <span class="label">域名</span>
                <span class="value copy-value" @click="copyToClipboard('999888.t.citmsp.com')">
                  999888.t.citmsp.com
                  <i class="el-icon-document-copy"></i>
                </span>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧监控图表区域 -->
        <el-col :span="16">
          <!-- 客户信息卡片 -->
          <el-card class="customer-card" shadow="never">
            <div slot="header" class="card-header">
              <span>客户</span>
            </div>
            <div class="customer-info">
              <div class="info-row">
                <div class="info-col">
                  <span class="label">客户名称</span>
                  <span class="value">{{currentResource.resourceName}}</span>
                </div>
                <div class="info-col">
                  <span class="label">企业ID</span>
                  <span class="value">{{currentResource.customerId}}</span>
                </div>
              </div>
              <div class="info-row">
                <div class="info-col">
                  <span class="label">企业描述</span>
                  <span class="value link-value">
                    娜娜集团企业描述
                    <i class="el-icon-edit-outline"></i>
                  </span>
                </div>
                <div class="info-col">
                  <span class="label">套餐类型</span>
                  <span class="value">畅云管家标准版</span>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 监控图表区域 -->
          <el-card class="monitor-card" shadow="never">
            <div slot="header" class="card-header">
              <span>监控</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="chart-container">
                  <div class="chart-title">CPU使用情况</div>
                  <div class="chart" ref="cpuChart"></div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="chart-container">
                  <div class="chart-title">内存使用情况</div>
                  <div class="chart" ref="memoryChart"></div>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="chart-container">
                  <div class="chart-title">带宽使用</div>
                  <div class="chart" ref="bandwidthChart"></div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="chart-container">
                  <div class="chart-title">磁盘使用</div>
                  <div class="chart" ref="diskChart"></div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { GetinstanceBatch } from "@/api/resell/orderinstance";
export default {
  name: 'ServerInfor',
  props: {
    currentResource: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      activeTab: 'monitor',
      charts: {
        cpu: null,
        memory: null,
        bandwidth: null,
        disk: null
      },
      // 遮罩层
      loading: true,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        resourceId:null,
        projectId:null,
        other1: null,
        other2: null,
        other3: null,
        other4: null,
        other5: null,
        ucode:null,
        ucodeiam:null,
        upsw:null,
        regionCode:null,

      },

      drawer: false,
      statelist: [],
      chatCupX:[],
      chatCupY:[],
      chatBandWidthX:[],
      chatBandWidthY:[],
    }
  },
  created() {

this.handleBatch();
  },
  mounted() {
    this.initCharts()
    // 模拟实时数据更新
    setInterval(() => {
      this.handleBatch()

    }, 300000)
  },
  methods: {
    initCharts() {
      // 初始化CPU使用率图表
      this.charts.cpu = echarts.init(this.$refs.cpuChart)
      this.charts.cpu.setOption({
        grid: {
          top: 30,
          right: 20,
          bottom: 30,
          left: 50
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: this.chatCupX,
          axisLabel: {
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [{
          data: this.chatCupY,
          type: 'line',
          smooth: true,
          name: 'CPU使用率(%)',
          color: '#409EFF'
        }]
      })

      // 初始化内存使用率图表
      this.charts.memory = echarts.init(this.$refs.memoryChart)
      this.charts.memory.setOption({
        grid: {
          top: 30,
          right: 20,
          bottom: 30,
          left: 50
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: this.getTimeData(),
          axisLabel: {
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [{
          data: this.generateRandomData(60, 10),
          type: 'line',
          smooth: true,
          name: '内存使用率(%)',
          color: '#67C23A'
        }]
      })

      // 初始化带宽使用图表
      this.charts.bandwidth = echarts.init(this.$refs.bandwidthChart)
      this.charts.bandwidth.setOption({
        grid: {
          top: 30,
          right: 20,
          bottom: 30,
          left: 50
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: this.chatBandWidthX,
          axisLabel: {
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [{
          data: this.chatBandWidthY,
          type: 'line',
          smooth: true,
          name: '带宽使用(Kb/s)',
          color: '#E6A23C'
        }]
      })

      // 初始化磁盘使用率图表
      this.charts.disk = echarts.init(this.$refs.diskChart)
      this.charts.disk.setOption({
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center'
        },
        series: [{
          type: 'pie',
          radius: ['60%', '80%'],
          avoidLabelOverlap: false,
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '12',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 15.6, name: '未使用' },
            { value: 24.4, name: '已使用' }
          ],
          color: ['#409EFF', '#67C23A']
        }]
      })
    },
    getTimeData() {
      const times = []
      const now = new Date()
      for (let i = 10; i >= 0; i--) {
        const time = new Date(now - i * 5 * 60 * 1000)
        times.push(time.toLocaleTimeString('zh-CN', { hour12: false }))
      }
      return times
    },
    generateRandomData(base, variance) {
      const data = []
      for (let i = 0; i < 11; i++) {
        data.push((base + Math.random() * variance).toFixed(1))
      }
      return data
    },

    updateCharts() {
      // 确保图表实例存在
      if (!this.charts.cpu || !this.charts.memory || !this.charts.bandwidth || !this.charts.disk) {
        this.initCharts()
        return
      }
      const newTime = new Date().toLocaleTimeString('zh-CN', { hour12: false })
      // 更新CPU图表
      this.charts.cpu.setOption({
        xAxis: {
          data: this.chatCupX
        },
        series: [{
          data: this.chatCupY
        }]
      })

      // 更新内存图表
      const memoryOption = this.charts.memory.getOption()
      memoryOption.xAxis[0].data.shift()
      memoryOption.xAxis[0].data.push(newTime)
      memoryOption.series[0].data.shift()
      memoryOption.series[0].data.push(this.generateRandomData(60, 10)[0])
      this.charts.memory.setOption(memoryOption)

      // 更新带宽图表
      this.charts.bandwidth.setOption({
        xAxis: {
          data: this.chatBandWidthX
        },
        series: [{
          data: this.chatBandWidthY
        }]
      })
    },
    handleBatch() {
      this.loading = false;
      this.queryParams.resourceId=this.currentResource.resourceId;
      this.queryParams.projectId=this.currentResource.projectId;

      this.queryParams.ucode=this.currentResource.ucode;
      this.queryParams.ucodeiam=this.currentResource.ucodeiam;
      this.queryParams.upsw=this.currentResource.upsw;
      this.queryParams.regionCode=this.currentResource.regionCode;
      this.queryParams.other1 ='1';
      this.queryParams.other2 = 'average';
      GetinstanceBatch(this.queryParams).then(response => {
        this.statelist = [];
        this.statelist = response.rows;
        this.statelist.forEach(element => {
          if (element.other1 == "cpu_util") {
            var tancelist = element.showinstance;
            tancelist.forEach(tval => {
              this.chatCupY.push(tval.other1);
              this.chatCupX.push(tval.other2);
            });
          }
        });
        this.statelist.forEach(element => {
          if (element.other1 == "disk_write_bytes_rate") {
            var tancelist = element.showinstance;
            tancelist.forEach(tval => {
              this.chatBandWidthY.push(tval.other1);
              this.chatBandWidthX.push(tval.other2);
              // other2fw.push(this.parseTime(element.other2, '{m}-{d}'))
            });
          }
        });


        this.updateCharts();

      });
    },
    copyToClipboard(text) {
      if (!text) return;

      // 创建临时文本区域
      const textArea = document.createElement('textarea');
      textArea.value = text;
      document.body.appendChild(textArea);

      try {
        // 选择文本
        textArea.select();
        textArea.setSelectionRange(0, 99999); // 兼容移动端

        // 执行复制命令
        const successful = document.execCommand('copy');

        if (successful) {
          this.$message({
            message: '复制成功',
            type: 'success',
            duration: 1500
          });
        } else {
          this.$message({
            message: '复制失败，请手动复制',
            type: 'warning',
            duration: 1500
          });
        }
      } catch (err) {
        this.$message({
          message: '复制失败，请手动复制',
          type: 'error',
          duration: 1500
        });
      } finally {
        // 清理临时文本区域
        document.body.removeChild(textArea);
      }
    },
  },
  beforeDestroy() {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize)
    // 销毁图表实例
    Object.values(this.charts).forEach(chart => {
      chart && chart.dispose()
    })
  }
}
</script>

<style scoped>
.monitor-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.nav-tabs {
  background: #fff;
  padding: 0 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.alert-info {
  margin-bottom: 20px;
}

.alert-link {
  margin-left: 10px;
}

.monitor-content {
  margin-top: 20px;
}

.info-card,
.security-card,
.network-card,
.customer-card,
.monitor-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
}

.info-list {
  font-size: 14px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  line-height: 1.4;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #6a93f5;
}

.value {
  color: #303133;
}

.copy-value {
  cursor: pointer;
  color: #409EFF;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: opacity 0.2s;
}

.copy-value:hover {
  opacity: 0.8;
}

.copy-value i {
  font-size: 14px;
  opacity: 0.6;
}

.copy-value:hover i {
  opacity: 1;
}

.security-content {
  display: flex;
  align-items: flex-start;
  gap: 30px;
}

.security-score {
  text-align: center;
}

.progress-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.percentage {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.unit {
  font-size: 12px;
  color: #769eee;
}

.status {
  font-size: 14px;
  color: #67C23A;
  margin-top: 4px;
}

.security-items {
  flex: 1;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.status-icon {
  color: #67C23A;
  margin-right: 4px;
}

.network-content,
.customer-info {
  font-size: 14px;
}

.ip-item,
.domain-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.info-row {
  display: flex;
  margin-bottom: 16px;
}

.info-col {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.link-value {
  color: #409EFF;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.chart-container {
  margin-bottom: 20px;
}

.chart-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.chart {
  height: 300px;
  background: #fff;
}

/* 响应式调整 */
@media screen and (max-width: 1400px) {
  .chart {
    height: 250px;
  }
}

@media screen and (max-width: 1200px) {
  .el-col-8 {
    width: 100%;
    margin-bottom: 20px;
  }

  .el-col-16 {
    width: 100%;
  }

  .security-content {
    flex-direction: column;
    align-items: center;
    gap: 20px;
  }

  .security-items {
    width: 100%;
  }
}

@media screen and (max-width: 768px) {
  .monitor-page {
    padding: 10px;
  }

  .info-row {
    flex-direction: column;
  }

  .info-col {
    margin-bottom: 12px;
  }

  .chart {
    height: 200px;
  }
}
</style>
